# 作者: Isearph
# 创建日期: 2025年6月13日
# 版本: 2.1.0.20250613
# 作者邮箱: 2665497226@qq.com


import tkinter
import calender_convert
import get_weather
from PIL import Image, ImageTk
import os
from tkinter import ttk


# 全局变量
label_img = None
custom_weather = None
custom_city = None
custom_year, custom_mon, custom_day, custom_week, \
        custom_LunarYear, custom_LunarMonth, custom_LunarDay, custom_leap, custom_solar_terms = \
        calender_convert.cal_paras(0, 2025, 1, 1)
today = [custom_year, custom_mon, custom_day]


def update_calender(custom):
    global ls_calender, custom_year, custom_mon, custom_day, custom_week, \
        custom_LunarYear, custom_LunarMonth, custom_LunarDay, custom_leap, custom_solar_terms

    custom_year, custom_mon, custom_day, custom_week, \
        custom_LunarYear, custom_LunarMonth, custom_LunarDay, custom_leap, custom_solar_terms = \
        calender_convert.cal_paras(custom, custom_year, custom_mon, custom_day)

    ls_calender[0] = calender_convert.LunarCalender(custom_year, custom_LunarMonth, custom_LunarDay, custom_leap, custom_solar_terms)
    ls_calender[1] = calender_convert.FR_CalendrierRepublicain(custom_year, custom_mon, custom_day)
    ls_calender[2] = calender_convert.CH_CalendrierRepublicain(custom_year, custom_mon, custom_day)
    ls_calender[3] = calender_convert.chinese_era(custom_year, custom_mon, custom_day, custom_LunarYear,
                                                  custom_LunarMonth, custom_LunarDay, custom_leap, custom_solar_terms)
    ls_calender[4] = calender_convert.japanese_era(custom_year, custom_mon, custom_day, custom_LunarYear,
                                                  custom_LunarMonth, custom_LunarDay, custom_leap, custom_solar_terms)
    ls_calender[5] = calender_convert.SolarCalender(custom_year, custom_mon, custom_day, custom_week, custom_solar_terms)


def change_calender():
    global option
    option = (option + 1) % 5
    lab_old_year.config(text=ls_calender[option][0])
    lab_old_monthday.config(text=ls_calender[option][1])
    show_images()
    root.event_generate('<<Event1>>')


def show_images():
    global label_img

    if cb2_var.get():
        image_name = ls_calender[5][2] if ls_calender[5][2] in calender_convert.jqmc else str(custom_mon)
    else:
        if option == 0 or (option == 3 and custom_year < 1912):
            image_name = ls_calender[option][2] if ls_calender[option][2] in calender_convert.jqmc else str(custom_LunarMonth)
        elif option == 3 and custom_year >= 1912:
            image_name = ls_calender[option][2] if ls_calender[option][2] in calender_convert.jqmc else str(custom_mon)
        elif option == 4:
            if custom_year >= 1873:
                image_name = ls_calender[option][2] if ls_calender[option][2] in calender_convert.jqmc else \
                    calender_convert.JapMonths[custom_mon-1]
            else:
                image_name = ls_calender[option][2] if ls_calender[option][2] in calender_convert.jqmc else \
                    calender_convert.JapMonths[custom_LunarMonth-1]
        elif option in [1, 2]:
            image_name = 'f11' if ls_calender[option][2] == -1 else ('f' + str(ls_calender[option][2]))
        else:
            print('error')

    image_path = f'images\\{image_name}.jpg'

    if os.path.exists(image_path):
        img_open = Image.open(image_path)
        img_jpg = ImageTk.PhotoImage(img_open)

        if label_img:
            label_img.config(image=img_jpg)
            label_img.image = img_jpg
        else:
            label_img = tkinter.Label(root, image=img_jpg)
            label_img.image = img_jpg
            label_img.place(x=250, y=30)  # 向下移动30像素为标题栏留出空间
    else:
        print(f"图片文件不存在: {image_path}")


def update_days(*args):
    global spinbox_year, spinbox_month, spinbox_day, custom_year, custom_mon, custom_day, custom_city

    custom_city = weather_box.get()

    try:
        custom_year = min(max(int(spinbox_year.get()), 1466), 2025)
        custom_mon = min(max(int(spinbox_month.get()), 1), 12)
    except ValueError:
        custom_year = 2025
        custom_mon = 1

    max_day = 31
    if custom_mon in [1, 3, 5, 7, 8, 10, 12]:
        max_day = 31
    elif custom_mon in [4, 6, 9, 11]:
        max_day = 30
    elif custom_mon == 2:
        max_day = 29 if calender_convert.is_leap(custom_year) else 28
    spinbox_day.config(to=max_day)

    try:
        custom_day = min(max(int(spinbox_day.get()), 1), max_day)
    except ValueError:
        custom_day = 1

    # if custom_day > max_day:
    #     spinbox_day.delete(0, "end")
    #     spinbox_day.insert(0, str(max_day))
    #     custom_day = max_day
    # if custom_day < 1:
    #     spinbox_day.delete(0, "end")
    #     spinbox_day.insert(0, 1)
    #     custom_day = 1

    update_calender(1)
    show_images()


def show_date_inputs():
    global spinbox_year, spinbox_month, spinbox_day, year_label, month_label, day_label

    date_frame = tkinter.Frame(root)
    date_frame.place(anchor='nw', x=30, y=45, height=60, width=220)  # 向下移动30像素

    spinbox_year = tkinter.Spinbox(date_frame, from_=1466, to=2025, width=4, command=update_days)
    spinbox_year.pack(side='left')
    year_label = tkinter.Label(date_frame, text='年', font=('华文行楷', 15))
    year_label.pack(side='left')
    spinbox_month = tkinter.Spinbox(date_frame, from_=1, to=12, width=2, command=update_days)
    spinbox_month.pack(side='left')
    month_label = tkinter.Label(date_frame, text='月', font=('华文行楷', 15))
    month_label.pack(side='left')
    spinbox_day = tkinter.Spinbox(date_frame, from_=1, to=31, width=2, command=update_days)
    spinbox_day.pack(side='left')
    day_label = tkinter.Label(date_frame, text='日', font=('华文行楷', 15))
    day_label.pack(side='left')

    spinbox_year.bind("<FocusOut>", update_days)
    spinbox_month.bind("<FocusOut>", update_days)
    spinbox_day.bind("<FocusOut>", update_days)

    lab_editweather.place(anchor='sw', x=0, y=150, height=25, width=250)
    weather_box.place(anchor='sw', x=0, y=175, height=25, width=250)
    weather_box['state'] = 'normal'

    def on_click_outside(event):
        clicked_widget = event.widget
        if clicked_widget not in [spinbox_year, spinbox_month, spinbox_day, weather_box]:
            root.focus_set()
            update_days()

    root.bind("<Button-1>", on_click_outside, "+")
    spinbox_year.delete(0, "end")
    spinbox_year.insert(0, str(custom_year))
    spinbox_month.delete(0, "end")
    spinbox_month.insert(0, str(custom_mon))
    spinbox_day.delete(0, "end")
    spinbox_day.insert(0, str(custom_day))


def hide_date_inputs():
    try:
        root.unbind("<Button-1>")
        spinbox_year.master.destroy()
        lab_editweather.place_forget()
        weather_box.place_forget()
    except:
        pass


def show_weather():
    global custom_year, custom_mon, custom_day
    if [custom_year, custom_mon, custom_day] == today:
    # if custom_year == today(0) and custom_mon == today(1) and custom_day == today(2):
        lab_city.place(anchor='sw', x=0, y=170, height=20, width=250)
        lab_temperature.place(anchor='sw', x=0, y=190, height=20, width=250)
        lab_weather.place(anchor='sw', x=0, y=210, height=20, width=250)
    else:
        lab_info.place(anchor='sw', x=0, y=190, height=20, width=250)


def hide_weather():
    lab_city.place_forget()
    lab_temperature.place_forget()
    lab_weather.place_forget()
    lab_info.place_forget()


def info_update():
    global cityInfo, temperatureInfo, weatherInfo, custom_city
    if custom_city == '' or None:
        pass
    elif cityInfo != get_weather.get_weather(custom_city)[0]:
        cityInfo, temperatureInfo, weatherInfo = \
            get_weather.get_weather(custom_city)[0], get_weather.get_weather(custom_city)[1], get_weather.get_weather(custom_city)[2]
        lab_city.config(text=cityInfo)
        lab_temperature.config(text=temperatureInfo)
        lab_weather.config(text=weatherInfo)
    else:
        pass


def setting_date():
    if cb1_var.get():
        hide_weather()
        lab_solar_year.place_forget()
        lab_solar_monthday.place_forget()
        show_date_inputs()
        cb2.config(state='disabled')
    else:
        hide_date_inputs()
        info_update()
        show_weather()
        lab_solar_year.config(
            text=calender_convert.SolarCalender(custom_year, custom_mon, custom_day, custom_week, custom_solar_terms)[0])
        lab_solar_monthday.config(
            text=calender_convert.SolarCalender(custom_year, custom_mon, custom_day, custom_week, custom_solar_terms)[1])
        lab_solar_year.place(anchor='nw', x=0, y=45, height=45, width=300)  # 向下移动30像素
        lab_solar_monthday.place(anchor='se', x=250, y=105, height=30, width=240)  # 向下移动30像素
        cb2.config(state='normal')


def solar_switch():
    if cb2_var.get():
        lab_old_year.place_forget()
        lab_old_monthday.place_forget()
        lab_solar_year.config(
            text=calender_convert.SolarCalender(custom_year, custom_mon, custom_day, custom_week, custom_solar_terms)[0])
        lab_solar_monthday.config(
            text=calender_convert.SolarCalender(custom_year, custom_mon, custom_day, custom_week, custom_solar_terms)[1])
        lab_solar_year.place(anchor='nw', x=0, y=45, height=60, width=300)  # 向下移动30像素
        lab_solar_monthday.place(anchor='se', x=250, y=105, height=30, width=240)  # 向下移动30像素
        cb1.config(state='normal')
        button1.config(state='disabled')
    else:
        lab_solar_year.place_forget()
        lab_solar_monthday.place_forget()
        lab_old_year.config(text=ls_calender[option][0])
        lab_old_monthday.config(text=ls_calender[option][1])
        lab_old_year.place(anchor='nw', x=0, y=45, height=60, width=300)  # 向下移动30像素
        lab_old_monthday.place(anchor='se', x=250, y=105, height=30, width=240)  # 向下移动30像素
        cb1.config(state='disabled')
        button1.config(state='normal')
    show_images()


# 窗口拖拽功能
def start_move(event):
    root.x = event.x
    root.y = event.y


def on_move(event):
    deltax = event.x - root.x
    deltay = event.y - root.y
    x = root.winfo_x() + deltax
    y = root.winfo_y() + deltay
    root.geometry(f"+{x}+{y}")


# 自定义按钮最小化绑定的函数
def window_iconic():
    root.overrideredirect(False)
    root.iconify()


# 监听窗口最大化或者正常模式的绑定事件
def window_normal(event):
    if root.state() == "normal" or root.state() == "zoomed":
        root.overrideredirect(True)


# 主程序
option = 0
ls_calender = [1, 2, 3, 4, 5, 6]

root = tkinter.Tk()
root.title('日历')
root.geometry('360x210')  # 增加高度以容纳标题栏
root.overrideredirect(True)  # 移除系统标题栏
root.iconbitmap(r'images/calender3.ico')

# 创建自定义标题栏
title_bar = tkinter.Frame(root, bg='#f0f0f0', relief='raised', bd=1, height=30)
title_bar.pack(fill='x', side='top')
title_bar.pack_propagate(False)

# 标题栏左侧 - 应用图标和标题
title_frame = tkinter.Frame(title_bar, bg='#f0f0f0')
title_frame.pack(side='left', fill='y')

# 添加应用图标（可选）
title_label = tkinter.Label(title_frame, text="日历", bg='#f0f0f0', fg='black', font=('微软雅黑', 9))
title_label.pack(side='left', padx=5, pady=5)

# 标题栏右侧 - 控制按钮
controls_frame = tkinter.Frame(title_bar, bg='#f0f0f0')
controls_frame.pack(side='right', fill='y')

# 将三个按钮放到标题栏
cb1_var = tkinter.BooleanVar()
cb1 = tkinter.Checkbutton(controls_frame, text="设置", command=setting_date, variable=cb1_var,
                             indicatoron=False, bg='#f0f0f0', relief='flat', bd=1, font=('微软雅黑', 8))
cb1.pack(side='left', padx=1, pady=2)

cb2_var = tkinter.BooleanVar()
cb2 = tkinter.Checkbutton(controls_frame, text="公历", command=solar_switch, variable=cb2_var,
                             indicatoron=False, bg='#f0f0f0', relief='flat', bd=1, font=('微软雅黑', 8))
cb2.pack(side='left', padx=1, pady=2)

button1 = tkinter.Button(controls_frame, text='切换', command=change_calender,
                            bg='#f0f0f0', relief='flat', bd=1, font=('微软雅黑', 8))
button1.pack(side='left', padx=1, pady=2)

# 关闭按钮（替代原来的最大化和关闭）
close_button = tkinter.Button(controls_frame, text='✕', command=root.quit,
                                 bg='#f0f0f0', fg='red', relief='flat', bd=1,
                                 font=('微软雅黑', 10), width=3)
close_button.pack(side='right', padx=2, pady=2)

# 最小化按钮
minimize_button = tkinter.Button(controls_frame, text='─', command=window_iconic,
                                    bg='#f0f0f0', relief='flat', bd=1,
                                    font=('微软雅黑', 10), width=3)
root.bind("<Configure>", window_normal)
root.bind("<Map>", window_normal)
minimize_button.pack(side='right', padx=1, pady=2)

# 让标题栏支持拖拽
title_bar.bind('<Button-1>', start_move)
title_bar.bind('<B1-Motion>', on_move)
title_label.bind('<Button-1>', start_move)
title_label.bind('<B1-Motion>', on_move)

    # # 加载背景图片
    # bg_image = Image.open(r"images/cloudy.jpg")  # 换成你图片路径
    # bg_image = ImageTk.PhotoImage(bg_image)
    #
    # # 用Label显示背景
    # background_label = tkinter.Label(root, image=bg_image)
    # background_label.place(x=0, y=0, relwidth=1, relheight=1)

# 其余控件的初始化
cb1.config(state='disabled')

update_calender(0)
lab_solar_year = tkinter.Label(root, anchor='nw', font=('华文行楷', 18),
        text=calender_convert.SolarCalender(custom_year, custom_mon, custom_day, custom_week, custom_solar_terms)[0])
lab_solar_monthday = tkinter.Label(root, anchor='se', font=('华文行楷', 15),
        text=calender_convert.SolarCalender(custom_year, custom_mon, custom_day, custom_week, custom_solar_terms)[1])

lab_old_year = tkinter.Label(root, text=ls_calender[option][0], anchor='nw', font=('华文行楷', 18))
lab_old_year.place(anchor='nw', x=0, y=45, height=60, width=300)  # 向下移动30像素
lab_old_monthday = tkinter.Label(root, text=ls_calender[option][1], anchor='se', font=('华文行楷', 15))
lab_old_monthday.place(anchor='se', x=250, y=105, height=30, width=240)  # 向下移动30像素

cityInfo, temperatureInfo, weatherInfo = get_weather.get_weather()[0], get_weather.get_weather()[1], get_weather.get_weather()[2]
lab_info = tkinter.Label(root, anchor='sw', font=('隶书', 12), text='无天气')
lab_info.place(anchor='sw', x=0, y=180, height=20, width=250)
lab_info.place_forget()
lab_city = tkinter.Label(root, anchor='sw', font=('隶书', 12), text=cityInfo)
lab_city.place(anchor='sw', x=0, y=170, height=20, width=250)
lab_temperature = tkinter.Label(root, anchor='sw', font=('隶书', 12), text=temperatureInfo)
lab_temperature.place(anchor='sw', x=0, y=190, height=20, width=250)
lab_weather = tkinter.Label(root, anchor='sw', font=('隶书', 12), text=weatherInfo)
lab_weather.place(anchor='sw', x=0, y=210, height=20, width=250)

lab_editweather = tkinter.Label(root, anchor='sw', font=('隶书', 15), text='更改城市')
lab_editweather.place(anchor='sw', x=0, y=150, height=25, width=250)
lab_editweather.place_forget()
weather_box = ttk.Combobox(root, values=get_weather.list_cities, state='normal')
weather_box.place(anchor='sw', x=0, y=175, height=25, width=250)
weather_box.place_forget()

show_images()

tkinter.mainloop()
